package org.wei.p2p.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.wei.p2p.account.entity.Account;
import org.wei.p2p.account.mapper.AccountMapper;
import org.wei.p2p.account.service.IAccountService;
import org.wei.p2p.account.service.SmsService;
import org.wei.p2p.api.account.model.AccountDTO;
import org.wei.p2p.api.account.model.AccountRegisterDTO;
import org.wei.p2p.api.account.model.VerificationInfoDTO;
import org.wei.p2p.common.utils.PasswordUtil;

import javax.annotation.Resource;

/**
 * @author wei
 * @date 2022/4/21 16:36
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    @Value("${sms.enable}")
    private Boolean smsEnable;
    @Resource
    private SmsService smsService;

    @Override
    public VerificationInfoDTO getSMSCode(String mobile) {
        return smsService.getSmsCode(mobile);
    }

    @Override
    public Integer checkMobile(String mobile, String key, String code) {
        smsService.verifySmsCode(key, code);
        LambdaQueryWrapper<Account> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Account::getMobile, mobile);
        return count(queryWrapper) > 0 ? 1 : 0;
    }

    @Override
    public AccountDTO register(AccountRegisterDTO registerDTO) {
        Account account=new Account();
        account.setUsername(registerDTO.getUsername());
        account.setMobile(registerDTO.getMobile());
        account.setPassword(PasswordUtil.generate(registerDTO.getPassword()));
        if(smsEnable){
            account.setPassword(PasswordUtil.generate(registerDTO.getMobile()));
        }
        account.setDomain("c");
        save(account);
        return convertAccountEntityToDTO(account);
    }

    private AccountDTO convertAccountEntityToDTO(Account entity) {
        if (entity == null) {
            return null;
        }
        AccountDTO dto = new AccountDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }
}
